package repository

import (
	"context"
	"database/sql"
	"fmt"
	"strconv"
	"strings"

	"mall/common/enumx"
	"mall/common/modelx"
	"mall/service/forum/model"

	"github.com/volatiletech/sqlboiler/v4/boil"
	"github.com/volatiletech/sqlboiler/v4/queries"
	"github.com/volatiletech/sqlboiler/v4/queries/qm"
	"github.com/zeromicro/go-zero/core/stores/cache"
)

type (
	// ForumTopicRepository is an interface to be customized, add more methods here,
	// and implement the added methods in customForumTopicRepository.
	ForumTopicRepository interface {
		Conn() error
		FindOne(
			ctx context.Context,
			id int64,
			asPreview bool,
			cols []string,
		) (*model.ForumTopic, error) /////
		GetList(
			ctx context.Context,
			cols model.M,
			withCount int,
			filter map[string]map[string][]any,
		) ([]*model.ForumTopic, int64, error) /////
		GetPostList(
			ctx context.Context,
			cols model.M,
			withCount int,
			filter map[string]map[string][]any,
		) ([]*model.ForumPost, int64, error) /////
		Insert(
			ctx context.Context,
			topic *model.ForumTopic,
			post *model.ForumPost,
			meta []*model.ForumTopicMetum,
			extra *model.ForumExtra,
		) (int64, error) //////
		Update(
			ctx context.Context,
			topic *model.ForumTopic,
			post *model.ForumPost,
			meta []*model.ForumTopicMetum,
			extra *model.ForumExtra,
		) (int64, error)
		UpdateBatch(
			ctx context.Context,
			cols model.M,
			filter map[string]map[string][]any,
		) (int64, error)
		BackendUpdateBatch(
			ctx context.Context,
			ids []uint64,
			cols model.M,
			extra *model.ForumExtra,
		) (int64, error)
		ForceDeleteBatch(ctx context.Context, ids []int64) (int64, error)
		GetMeta(
			ctx context.Context,
			cols model.M,
			withCount int,
			filter map[string]map[string][]any,
		) ([]*model.ForumTopicMetum, int64, error)
		IncreaseMeta(ctx context.Context, ids []int64, metaKey string, step int) (int64, error) //////
		DecreaseMeta(ctx context.Context, ids []int64, metaKey string, step int) (int64, error) //////
		GetMedia(
			ctx context.Context,
			cols model.M,
			withCount int,
			filter map[string]map[string][]any,
		) ([]*model.ForumAttachmentRelationship, int64, error)
	}

	customForumTopicRepository struct {
		cacheConf  cache.CacheConf
		dataSource string

		mysqlConn *sql.DB
	}
)

// NewForumTopicRepository returns a repository for the database table.
func NewForumTopicRepository(dataSource string, cacheConf cache.CacheConf) ForumTopicRepository {
	return &customForumTopicRepository{
		cacheConf:  cacheConf,
		dataSource: dataSource,
	}
}

func (r *customForumTopicRepository) Conn() error {
	if r.mysqlConn == nil {
		mysqlConn, err := modelx.NewMysqlConn(r.dataSource)
		if err != nil {
			return err
		}

		r.mysqlConn = mysqlConn
	}

	return nil
}

func (r *customForumTopicRepository) FindOne(
	ctx context.Context,
	id int64,
	asPreview bool,
	cols []string,
) (topic *model.ForumTopic, err error) {
	if err = r.Conn(); err != nil {
		return
	}

	topic, err = model.FindForumTopic(ctx, r.mysqlConn, uint64(id), cols...)
	if err != nil {
		return
	}

	if asPreview || topic.TopicStatus == uint8(enumx.ObjectStatusAproved) {
		return
	}

	return nil, nil
}

func (r *customForumTopicRepository) GetList(
	ctx context.Context,
	cols model.M,
	withCount int,
	filter map[string]map[string][]any,
) (list []*model.ForumTopic, count int64, err error) {
	if err = r.Conn(); err != nil {
		return
	}

	var mods []qm.QueryMod
	var page int
	var pageSize int
	var offset int
	var limit int
	var selectCol string
	for k, v := range cols {
		switch k {
		case "page":
			if val, ok := v.(int64); ok && val > 1 {
				page = int(val)
			}
		case "pageSize":
			if val, ok := v.(int64); ok && val > 0 {
				pageSize = int(val)
			}
		case "offset":
			if val, ok := v.(int32); ok && val > 0 {
				offset = int(val)
			}
		case "limit":
			if val, ok := v.(int32); ok && val > 0 {
				limit = int(val)
			}
		case "orderBy":
			if val, ok := v.(string); ok && val != "" {
				mods = append(mods, qm.OrderBy(val))
			}
		case "select":
			if val, ok := v.(string); ok && val != "" {
				selectCol = val
			}
		case "asPreview":
			if val, ok := v.(string); ok && val == "" { // 不是预览，必须是已发布
				mods = append(mods, model.ForumTopicWhere.TopicStatus.EQ(uint8(enumx.ObjectStatusAproved)))
			}
		case "search":
			if val, ok := v.(string); ok && val != "" { // 搜索
				likeVal := fmt.Sprintf("%%%s%%", val)
				mods = append(mods, qm.Where(fmt.Sprintf(
					"(%s LIKE ? OR %s LIKE ?)",
					model.ForumTopicColumns.Title,
					model.ForumTopicColumns.Slug), likeVal, likeVal))
			}
		}
	}

	for key, opMap := range filter {
		switch key {
		case model.ForumTopicColumns.TopicID:
			mods = append(mods, modelx.GetIntMods(model.ForumTopicColumns.TopicID, opMap)...)
		case model.ForumTopicColumns.ForumID:
			mods = append(mods, modelx.GetIntMods(model.ForumTopicColumns.ForumID, opMap)...)
		case model.ForumTopicColumns.TopicAuthorID:
			mods = append(mods, modelx.GetIntMods(model.ForumTopicColumns.TopicAuthorID, opMap)...)
		case model.ForumTopicColumns.TopicAuthorNickname:
			mods = append(mods, modelx.GetStringMods(model.ForumTopicColumns.TopicAuthorNickname, opMap)...)
		case model.ForumTopicColumns.Title:
			mods = append(mods, modelx.GetStringMods(model.ForumTopicColumns.Title, opMap)...)
		case model.ForumTopicColumns.Slug:
			mods = append(mods, modelx.GetStringMods(model.ForumTopicColumns.Slug, opMap)...)
		case model.ForumTopicColumns.TopicStatus:
			mods = append(mods, modelx.GetIntMods(model.ForumTopicColumns.TopicStatus, opMap)...)
		}
	}

	if withCount >= 0 {
		if withCount >= 2 {
			var nextCount int64
			var previousCount int64
			subMods := make([]qm.QueryMod, len(mods), len(mods)+3)
			copy(subMods, mods)
			subMods = append(subMods, qm.Limit(1))
			subMods = append(subMods, qm.Select(model.ForumTopicColumns.TopicID))

			if withCount != 3 && offset >= 1 {
				subMods = append(subMods, qm.Offset(offset-1))
				previousList, previousErr := model.ForumTopics(subMods...).All(ctx, r.mysqlConn)
				if previousErr != nil {
					err = previousErr
					return
				}

				if len(previousList) > 0 {
					previousCount = 1
				}
			}
			if limit > 0 {
				subMods = append(subMods, qm.Offset(offset+limit))
				nextList, nextErr := model.ForumTopics(subMods...).All(ctx, r.mysqlConn)
				if nextErr != nil {
					err = nextErr
					return
				}

				if len(nextList) > 0 {
					nextCount = 1
				}
			}

			count = previousCount + nextCount*2
		} else {
			count, err = model.ForumTopics(mods...).Count(ctx, r.mysqlConn)
			if err != nil {
				if err == sql.ErrNoRows {
					err = nil
					return
				}

				return
			}

			if withCount == 0 {
				return
			}
		}
	}

	if pageSize > 0 {
		if page > 1 {
			mods = append(mods, qm.Offset(pageSize*(page-1)))
		}
		mods = append(mods, qm.Limit(pageSize))
	} else if limit > 0 || offset > 0 {
		if limit > 0 {
			mods = append(mods, qm.Limit(limit))
		}
		if offset > 0 {
			mods = append(mods, qm.Offset(offset))
		}
	}

	var columns []string
	if selectCol != "" {
		if selectCol != "," {
			columns = strings.Split(selectCol, ",")
		}
		columns = append(columns, model.ForumTopicColumns.TopicID)
	}
	if len(columns) > 0 {
		mods = append(mods, qm.Select(columns...))
	}

	list, err = model.ForumTopics(mods...).All(ctx, r.mysqlConn)
	return
}

func (r *customForumTopicRepository) GetPostList(
	ctx context.Context,
	cols model.M,
	withCount int,
	filter map[string]map[string][]any,
) (list []*model.ForumPost, count int64, err error) {
	if err = r.Conn(); err != nil {
		return
	}

	var mods []qm.QueryMod
	var page int
	var pageSize int
	var offset int
	var limit int
	var selectCol string
	for k, v := range cols {
		switch k {
		case "page":
			if val, ok := v.(int64); ok && val > 1 {
				page = int(val)
			}
		case "pageSize":
			if val, ok := v.(int64); ok && val > 0 {
				pageSize = int(val)
			}
		case "offset":
			if val, ok := v.(int32); ok && val > 0 {
				offset = int(val)
			}
		case "limit":
			if val, ok := v.(int32); ok && val > 0 {
				limit = int(val)
			}
		case "orderBy":
			if val, ok := v.(string); ok && val != "" {
				mods = append(mods, qm.OrderBy(val))
			}
		case "select":
			if val, ok := v.(string); ok && val != "" {
				selectCol = val
			}
		case "asPreview":
			if val, ok := v.(uint64); ok && val > 0 {
				mods = append(mods, qm.Where(fmt.Sprintf(
					"(%s = ? OR %s = ?)",
					model.ForumPostColumns.PostAuthorID,
					model.ForumPostColumns.PostStatus), val, uint8(enumx.ObjectStatusAproved)))
			} else { // 不是预览，必须是已发布
				mods = append(mods, model.ForumPostWhere.PostStatus.EQ(uint8(enumx.ObjectStatusAproved)))
			}
		}
	}

	for key, opMap := range filter {
		switch key {
		case model.ForumPostColumns.PostID:
			mods = append(mods, modelx.GetIntMods(model.ForumPostColumns.PostID, opMap)...)
		case model.ForumPostColumns.ForumID:
			mods = append(mods, modelx.GetIntMods(model.ForumPostColumns.ForumID, opMap)...)
		case model.ForumPostColumns.TopicID:
			mods = append(mods, modelx.GetIntMods(model.ForumPostColumns.TopicID, opMap)...)
		case model.ForumPostColumns.ParentID:
			mods = append(mods, modelx.GetIntMods(model.ForumPostColumns.ParentID, opMap)...)
		case model.ForumPostColumns.PostAuthorID:
			mods = append(mods, modelx.GetIntMods(model.ForumPostColumns.PostAuthorID, opMap)...)
		case model.ForumPostColumns.PostAuthorNickname:
			mods = append(mods, modelx.GetStringMods(model.ForumPostColumns.PostAuthorNickname, opMap)...)
		case model.ForumPostColumns.PostStatus:
			mods = append(mods, modelx.GetIntMods(model.ForumPostColumns.PostStatus, opMap)...)
		case model.ForumPostColumns.CommentStatus:
			mods = append(mods, modelx.GetIntMods(model.ForumPostColumns.CommentStatus, opMap)...)
		}
	}

	if withCount >= 0 {
		if withCount >= 2 {
			var nextCount int64
			var previousCount int64
			subMods := make([]qm.QueryMod, len(mods), len(mods)+3)
			copy(subMods, mods)
			subMods = append(subMods, qm.Limit(1))
			subMods = append(subMods, qm.Select(model.ForumPostColumns.PostID))

			if withCount != 3 && offset >= 1 {
				subMods = append(subMods, qm.Offset(offset-1))
				previousList, previousErr := model.ForumPosts(subMods...).All(ctx, r.mysqlConn)
				if previousErr != nil {
					err = previousErr
					return
				}
				if len(previousList) > 0 {
					previousCount = 1
				}
			}
			if limit > 0 {
				subMods = append(subMods, qm.Offset(offset+limit))
				nextList, nextErr := model.ForumPosts(subMods...).All(ctx, r.mysqlConn)
				if nextErr != nil {
					err = nextErr
					return
				}
				if len(nextList) > 0 {
					nextCount = 1
				}
			}

			count = previousCount + nextCount*2
		} else {
			count, err = model.ForumPosts(mods...).Count(ctx, r.mysqlConn)
			if err != nil {
				return
			}

			if withCount == 0 {
				return
			}
		}
	}

	if pageSize > 0 {
		if page > 1 {
			mods = append(mods, qm.Offset(pageSize*(page-1)))
		}
		mods = append(mods, qm.Limit(pageSize))
	} else if limit > 0 || offset > 0 {
		if limit > 0 {
			mods = append(mods, qm.Limit(limit))
		}
		if offset > 0 {
			mods = append(mods, qm.Offset(offset))
		}
	}

	var columns []string
	if selectCol != "" {
		if selectCol != "," {
			columns = strings.Split(selectCol, ",")
		}
		columns = append(columns, model.ForumPostColumns.PostID)
	}
	if len(columns) > 0 {
		mods = append(mods, qm.Select(columns...))
	}

	list, err = model.ForumPosts(mods...).All(ctx, r.mysqlConn)
	return
}

func (r *customForumTopicRepository) Insert(
	ctx context.Context,
	topic *model.ForumTopic,
	post *model.ForumPost,
	meta []*model.ForumTopicMetum,
	extra *model.ForumExtra,
) (topicId int64, err error) {
	if err = r.Conn(); err != nil {
		return
	}

	tx, err := r.mysqlConn.BeginTx(ctx, nil)
	if err != nil {
		return
	}

	err = topic.Insert(ctx, tx, boil.Infer())
	if err != nil {
		tx.Rollback()
		return
	}

	tid := topic.TopicID
	topicId = int64(tid)
	if post != nil && len(post.PostContent) > 0 {
		post.TopicID = tid
		err = post.Insert(ctx, tx, boil.Infer())
		if err != nil {
			tx.Rollback()
			return
		}
	}

	if len(meta) > 0 {
		for _, m := range meta {
			m.TopicID = tid
			err = m.Insert(ctx, tx, boil.Infer())
			if err != nil {
				tx.Rollback()
				return
			}
		}
	}

	if len(extra.Media) > 0 {
		for _, m := range extra.Media {
			m.ObjectID = tid
			m.ObjectType = uint16(enumx.ObjectTypeTopic)
			err = m.Insert(ctx, tx, boil.Infer())
			if err != nil {
				tx.Rollback()
				return
			}
		}
	}

	tx.Commit()
	return
}

func (r *customForumTopicRepository) Update(
	ctx context.Context,
	topic *model.ForumTopic,
	post *model.ForumPost,
	meta []*model.ForumTopicMetum,
	extra *model.ForumExtra,
) (int64, error) {
	if err := r.Conn(); err != nil {
		return 0, err
	}

	tx, err := r.mysqlConn.BeginTx(ctx, nil)
	if err != nil {
		return 0, err
	}

	topicId, err := topic.Update(ctx, tx, boil.Blacklist(
		model.ForumTopicColumns.TopicID,
		model.ForumTopicColumns.ForumID,
		model.ForumTopicColumns.TopicAuthorID,
		model.ForumTopicColumns.TopicAuthorNickname,
		model.ForumTopicColumns.TopicAuthorEmail,
		model.ForumTopicColumns.TopicAuthorAvatar,
		model.ForumTopicColumns.TopicAuthorIP,
		model.ForumTopicColumns.TopicDate,
		model.ForumTopicColumns.TopicDateGMT,
		model.ForumTopicColumns.PostCount,
		model.ForumTopicColumns.ViewCount,
		model.ForumTopicColumns.CommentCount,
	))
	if err != nil {
		tx.Rollback()
		return 0, err
	}

	tid := topic.TopicID
	if post != nil {
		_, err := post.Update(ctx, tx, boil.Blacklist(
			model.ForumPostColumns.PostID,
			model.ForumPostColumns.ForumID,
			model.ForumPostColumns.TopicID,
			model.ForumPostColumns.ParentID,
			model.ForumPostColumns.PostAuthorID,
			model.ForumPostColumns.PostAuthorNickname,
			model.ForumPostColumns.PostAuthorEmail,
			model.ForumPostColumns.PostAuthorAvatar,
			model.ForumPostColumns.PostAuthorIP,
			model.ForumPostColumns.PostDate,
			model.ForumPostColumns.PostDateGMT,
			model.ForumPostColumns.CommentCount,
		))
		if err != nil {
			tx.Rollback()
			return 0, err
		}
	}

	if len(meta) > 0 {
		for _, m := range meta {
			if m.MetaID > 0 {
				_, err = m.Update(ctx, tx, boil.Blacklist(
					model.ForumTopicMetumColumns.MetaID,
					model.ForumTopicMetumColumns.TopicID,
				))
			} else {
				m.TopicID = tid
				err = m.Insert(ctx, tx, boil.Infer())
			}
			if err != nil {
				tx.Rollback()
				return 0, err
			}
		}
	}
	if len(extra.Media) > 0 {
		for _, m := range extra.Media {
			if m.AttachmentRelationshipID > 0 {
				_, err = m.Update(ctx, tx, boil.Blacklist(
					model.ForumAttachmentRelationshipColumns.AttachmentRelationshipID,
					model.ForumAttachmentRelationshipColumns.ObjectID,
					model.ForumAttachmentRelationshipColumns.ObjectType,
					model.ForumAttachmentRelationshipColumns.AttachmentID,
				))
			} else {
				m.ObjectID = tid
				m.ObjectType = uint16(enumx.ObjectTypeTopic)
				err = m.Insert(ctx, tx, boil.Infer())
			}
			if err != nil {
				tx.Rollback()
				return 0, err
			}
		}
	}
	if len(extra.DelMetaIds) > 0 {
		ids := make([]any, 0, len(extra.DelMetaIds))
		for _, id := range extra.DelMetaIds {
			ids = append(ids, id)
		}
		var mods []qm.QueryMod
		mods = append(mods, qm.WhereIn(fmt.Sprintf("%s IN ?", model.ForumTopicMetumColumns.MetaID), ids...))
		_, err := model.ForumTopicMeta(mods...).DeleteAll(ctx, tx)
		if err != nil {
			tx.Rollback()
			return 0, err
		}
	}
	if len(extra.DelMediaIds) > 0 {
		ids := make([]any, 0, len(extra.DelMediaIds))
		for _, id := range extra.DelMediaIds {
			ids = append(ids, id)
		}
		var mods []qm.QueryMod
		mods = append(mods, qm.WhereIn(fmt.Sprintf("%s IN ?", model.ForumAttachmentRelationshipColumns.AttachmentRelationshipID), ids...))
		_, err := model.ForumAttachmentRelationships(mods...).DeleteAll(ctx, tx)
		if err != nil {
			tx.Rollback()
			return 0, err
		}
	}

	tx.Commit()
	return topicId, nil
}

func (r *customForumTopicRepository) UpdateBatch(
	ctx context.Context,
	cols model.M,
	filter map[string]map[string][]any,
) (rowsAff int64, err error) {
	if err = r.Conn(); err != nil {
		return
	}

	var mods []qm.QueryMod
	for key, opMap := range filter {
		switch key {
		case model.ForumTopicColumns.TopicID:
			mods = append(mods, modelx.GetIntMods(model.ForumTopicColumns.TopicID, opMap)...)
		case model.ForumTopicColumns.ForumID:
			mods = append(mods, modelx.GetIntMods(model.ForumTopicColumns.ForumID, opMap)...)
		case model.ForumTopicColumns.TopicAuthorID:
			mods = append(mods, modelx.GetIntMods(model.ForumTopicColumns.TopicAuthorID, opMap)...)
		case model.ForumTopicColumns.TopicAuthorNickname:
			mods = append(mods, modelx.GetStringMods(model.ForumTopicColumns.TopicAuthorNickname, opMap)...)
		case model.ForumTopicColumns.Title:
			mods = append(mods, modelx.GetStringMods(model.ForumTopicColumns.Title, opMap)...)
		case model.ForumTopicColumns.Slug:
			mods = append(mods, modelx.GetStringMods(model.ForumTopicColumns.Slug, opMap)...)
		case model.ForumTopicColumns.TopicStatus:
			mods = append(mods, modelx.GetIntMods(model.ForumTopicColumns.TopicStatus, opMap)...)
		case model.ForumTopicColumns.Sticky:
			mods = append(mods, modelx.GetIntMods(model.ForumTopicColumns.Sticky, opMap)...)
		}
	}
	if len(mods) == 0 {
		return
	}

	rowsAff, err = model.ForumTopics(mods...).UpdateAll(ctx, r.mysqlConn, cols)
	return
}

func (r *customForumTopicRepository) BackendUpdateBatch(
	ctx context.Context,
	ids []uint64,
	cols model.M,
	extra *model.ForumExtra,
) (rowsAff int64, err error) {
	if err = r.Conn(); err != nil {
		return
	}

	if len(ids) > 0 {
		tx, txErr := r.mysqlConn.BeginTx(ctx, nil)
		if txErr != nil {
			err = txErr
			return
		}

		var mods []qm.QueryMod
		mods = append(mods, model.ForumTopicWhere.TopicID.IN(ids))
		rowsAff, err = model.ForumTopics(mods...).UpdateAll(ctx, tx, cols)
		if err != nil {
			tx.Rollback()
			return 0, err
		}

		if len(extra.TopicLogs) > 0 {
			for _, log := range extra.TopicLogs {
				err = log.Insert(ctx, tx, boil.Infer())
				if err != nil {
					tx.Rollback()
					return 0, err
				}
			}
		}

		if len(extra.Notices) > 0 {
			for _, notice := range extra.Notices {
				err = notice.Insert(ctx, tx, boil.Infer())
				if err != nil {
					tx.Rollback()
					return 0, err
				}
			}
		}

		tx.Commit()
		return
	}

	return
}

func (r *customForumTopicRepository) ForceDeleteBatch(ctx context.Context, ids []int64) (rowsAff int64, err error) {
	if err = r.Conn(); err != nil {
		return
	}

	var mods []qm.QueryMod
	if len(ids) > 0 {
		values := make([]any, 0, len(ids))
		for _, id := range ids {
			values = append(values, uint64(id))
		}

		mods = append(mods, qm.WhereIn(fmt.Sprintf("%s IN ?", model.ForumTopicColumns.TopicID), values...))
	}

	rowsAff, err = model.ForumTopics(mods...).DeleteAll(ctx, r.mysqlConn)
	return
}

func (r *customForumTopicRepository) GetMeta(
	ctx context.Context,
	cols model.M,
	withCount int,
	filter map[string]map[string][]any,
) (list []*model.ForumTopicMetum, count int64, err error) {
	if err = r.Conn(); err != nil {
		return
	}

	var mods []qm.QueryMod
	var page int
	var pageSize int
	var selectCol string
	for k, v := range cols {
		switch k {
		case "page":
			if val, ok := v.(int64); ok && val > 1 {
				page = int(val)
			}
		case "pageSize":
			if val, ok := v.(int64); ok && val > 0 {
				pageSize = int(val)
			}
		case "orderBy":
			if val, ok := v.(string); ok && val != "" {
				mods = append(mods, qm.OrderBy(val))
			}
		case "select":
			if val, ok := v.(string); ok && val != "" {
				selectCol = val
			}
		}
	}

	for key, opMap := range filter {
		switch key {
		case model.ForumTopicMetumColumns.MetaID:
			mods = append(mods, modelx.GetIntMods(model.ForumTopicMetumColumns.MetaID, opMap)...)
		case model.ForumTopicMetumColumns.TopicID:
			mods = append(mods, modelx.GetIntMods(model.ForumTopicMetumColumns.TopicID, opMap)...)
		case model.ForumTopicMetumColumns.MetaKey:
			mods = append(mods, modelx.GetStringMods(model.ForumTopicMetumColumns.MetaKey, opMap)...)
		}
	}

	if withCount >= 0 {
		count, err = model.ForumTopicMeta(mods...).Count(ctx, r.mysqlConn)
		if err != nil {
			return
		}

		if withCount == 0 {
			return
		}
	}

	if pageSize > 0 {
		if page > 1 {
			mods = append(mods, qm.Offset(pageSize*(page-1)))
		}
		mods = append(mods, qm.Limit(pageSize))
	}

	var columns []string
	if selectCol != "" {
		if selectCol != "," {
			columns = strings.Split(selectCol, ",")
		}
		columns = append(columns, model.ForumTopicMetumColumns.MetaID)
	}
	if len(columns) > 0 {
		mods = append(mods, qm.Select(columns...))
	}

	list, err = model.ForumTopicMeta(mods...).All(ctx, r.mysqlConn)
	return
}

func (r *customForumTopicRepository) IncreaseMeta(
	ctx context.Context,
	ids []int64,
	metaKey string,
	step int,
) (rowsAff int64, err error) {
	if err = r.Conn(); err != nil {
		return
	}

	if len(ids) > 0 {
		tids := make([]string, 0, len(ids))
		for _, id := range ids {
			tids = append(tids, strconv.FormatInt(id, 10))
		}
		var info RandomInfo
		err = queries.Raw(fmt.Sprintf(
			`update %s set %s=%s+%d where %s="%s" and %s in (%s)`,
			model.TableNames.ForumTopicMeta,
			model.ForumTopicMetumColumns.MetaValue,
			model.ForumTopicMetumColumns.MetaValue,
			step,
			model.ForumTopicMetumColumns.MetaKey,
			metaKey,
			model.ForumTopicMetumColumns.TopicID,
			strings.Join(tids, ","),
		)).Bind(ctx, r.mysqlConn, &info)

		if err == sql.ErrNoRows {
			return 0, model.ErrNotFound
		}
	}

	return
}

func (r *customForumTopicRepository) DecreaseMeta(
	ctx context.Context,
	ids []int64,
	metaKey string,
	step int,
) (rowsAff int64, err error) {
	if err = r.Conn(); err != nil {
		return
	}

	if len(ids) > 0 {
		tids := make([]string, 0, len(ids))
		for _, id := range ids {
			tids = append(tids, strconv.FormatInt(id, 10))
		}
		var info RandomInfo
		err = queries.Raw(fmt.Sprintf(
			`update %s set %s=%s-%d where %s="%s" and %s in (%s)`,
			model.TableNames.ForumTopicMeta,
			model.ForumTopicMetumColumns.MetaValue,
			model.ForumTopicMetumColumns.MetaValue,
			step,
			model.ForumTopicMetumColumns.MetaKey,
			metaKey,
			model.ForumTopicMetumColumns.TopicID,
			strings.Join(tids, ","),
		)).Bind(ctx, r.mysqlConn, &info)

		if err == sql.ErrNoRows {
			return 0, model.ErrNotFound
		}
	}

	return
}

func (r *customForumTopicRepository) GetMedia(
	ctx context.Context,
	cols model.M,
	withCount int,
	filter map[string]map[string][]any,
) (list []*model.ForumAttachmentRelationship, count int64, err error) {
	if err = r.Conn(); err != nil {
		return
	}

	var mods []qm.QueryMod
	var page int
	var pageSize int
	var selectCol string
	for k, v := range cols {
		switch k {
		case "page":
			if val, ok := v.(int64); ok && val > 1 {
				page = int(val)
			}
		case "pageSize":
			if val, ok := v.(int64); ok && val > 0 {
				pageSize = int(val)
			}
		case "orderBy":
			if val, ok := v.(string); ok && val != "" {
				mods = append(mods, qm.OrderBy(val))
			}
		case "select":
			if val, ok := v.(string); ok && val != "" {
				selectCol = val
			}
		}
	}

	for key, opMap := range filter {
		switch key {
		case model.ForumAttachmentRelationshipColumns.AttachmentRelationshipID:
			mods = append(mods, modelx.GetIntMods(model.ForumAttachmentRelationshipColumns.AttachmentRelationshipID, opMap)...)
		case model.ForumAttachmentRelationshipColumns.ObjectID:
			mods = append(mods, modelx.GetIntMods(model.ForumAttachmentRelationshipColumns.ObjectID, opMap)...)
		case model.ForumAttachmentRelationshipColumns.ObjectType:
			mods = append(mods, modelx.GetIntMods(model.ForumAttachmentRelationshipColumns.ObjectType, opMap)...)
		case model.ForumAttachmentRelationshipColumns.AttachmentID:
			mods = append(mods, modelx.GetIntMods(model.ForumAttachmentRelationshipColumns.AttachmentID, opMap)...)
		case model.ForumAttachmentRelationshipColumns.AttachmentThumbnail:
			mods = append(mods, modelx.GetIntMods(model.ForumAttachmentRelationshipColumns.AttachmentThumbnail, opMap)...)
		case model.ForumAttachmentRelationshipColumns.AttachmentOrder:
			mods = append(mods, modelx.GetIntMods(model.ForumAttachmentRelationshipColumns.AttachmentOrder, opMap)...)
		}
	}

	if withCount >= 0 {
		count, err = model.ForumAttachmentRelationships(mods...).Count(ctx, r.mysqlConn)
		if err != nil {
			return
		}

		if withCount == 0 {
			return
		}
	}

	if pageSize > 0 {
		if page > 1 {
			mods = append(mods, qm.Offset(pageSize*(page-1)))
		}
		mods = append(mods, qm.Limit(pageSize))
	}

	var columns []string
	if selectCol != "" {
		if selectCol != "," {
			columns = strings.Split(selectCol, ",")
		}
		columns = append(columns, model.ForumAttachmentRelationshipColumns.AttachmentRelationshipID)
		columns = append(columns, model.ForumAttachmentRelationshipColumns.ObjectID)
	}
	if len(columns) > 0 {
		mods = append(mods, qm.Select(columns...))
	}

	list, err = model.ForumAttachmentRelationships(mods...).All(ctx, r.mysqlConn)
	return
}
